<?php
class ProductsController extends AppController {
	var $name = 'Products'; 
	var $uses = array('Product','Order'); // 2009/10/28 追加
	var $helpers = array('Html', 'Form','Text','Number','Time');
	var $components = array('Auth');
    function beforeFilter(){
		parent::beforeFilter();
    }
	function admin_index() {
		$this->Product->recursive = 0;
		$this->set('products', $this->paginate());
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Product.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('product', $this->Product->read(null, $id));
	}

	function admin_add() {
		if (!empty($this->data)) {
			$this->Product->create();
			if ($this->Product->save($this->data)) {
				$this->Session->setFlash(__('The Product has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Product could not be saved. Please, try again.', true));
			}
		}
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Product', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Product->save($this->data)) {
				$this->Session->setFlash(__('The Product has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Product could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Product->read(null, $id);
		}
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Product', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Product->del($id)) {
			$this->Session->setFlash(__('Product deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}
	
	function admin_ship(){
		$count = 0;
		if( !empty($this->data)){
			$things_to_ship = $this->data['Order'];
			if( !empty($things_to_ship)){
				$count = $this->do_shipping($things_to_ship);
				if( $count > 0 ){
					$this->Session->setFlash("$count 件の注文が発送済みとしてマークされました");
				}
			}
		}
		#$pending_orders = $this->Order->findAllByShippedAt(NULL);
		#debug($pending_orders);
		$this->set('pending_orders',$this->Order->pending_shipping());
	}
	private function do_shipping($things_to_ship){
		$count = 0;
		//debug($things_to_ship);
		$this->Order->saveAll($things_to_ship);
		# 件数をカウント
		foreach($things_to_ship as $order ){
			if( $order['to_be_shipped'] == 1 ){
				$count++;
			}
		}
		return $count;
	}
}
?>